package com.qf.fmall2202.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qf.fmall2202.ex.QFException;
import com.qf.fmall2202.user.entity.User;
import com.qf.fmall2202.user.mapper.UsersMapper;
import com.qf.fmall2202.user.service.IUsersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.fmall2202.user.shiro.ShiroConstants;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.UUID;

/**
 * <p>
 * 用户  服务实现类
 * </p>
 *
 * @author dong_
 * @since 2022-11-03
 */
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, User> implements IUsersService {

    @Transactional(rollbackFor = Exception.class)
    @Override
    public User regist(User user) {

        //1. 比对密码是否一致
        final String password = user.getPassword();
        final String repassword = user.getRepassword();
        if ( !(password!=null&&password.equals(repassword)) ){
            // 密码有问题，两次密码不一致
            throw new QFException("密码有问题，两次密码不一致");
        }

        //2. 检查用户名是否存在
//        final User dbUser = this.getOne(new LambdaQueryWrapper<User>().eq(User::getUsername, user.getUsername()));
        final User dbUser = this.getOne(new QueryWrapper<User>().eq("username",user.getUsername()));
        if (dbUser!=null){
            throw new QFException("用户名重复了");
        }

        //3. 生成salt，对密码进行加密处理
        final String salt = UUID.randomUUID().toString().replaceAll("-", "");
        final Md5Hash md5Hash = new Md5Hash(password, salt, ShiroConstants.HASH_TIMES);
        final String shiroPassword = md5Hash.toHex();

        //4. 保存用户数据到数据库
        user.setSalt(salt);
        user.setPassword(shiroPassword);

        user.setUserRegtime(new Date());
        user.setUserModtime(new Date());

        this.save(user);

        return user;
    }
}
